//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import CardWrap from "@/components/CardWrap";
import { Button, message, Popover, Space, Table } from "antd";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import type { ShareInfo } from "@/api/project_share";
import { get_type_name, list_share, remove_share, SHARE_TARGET_BUG, SHARE_TARGET_DOC, SHARE_TARGET_DRAW, SHARE_TARGET_REQUIRE_MENT, SHARE_TARGET_TASK, SHARE_TARGET_WORK_PLAN } from "@/api/project_share";
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import moment from "moment";
import { open as shell_open } from '@tauri-apps/api/shell';
import { writeText } from '@tauri-apps/api/clipboard';
import { useHistory } from "react-router-dom";
import { LinkBugInfo, LinkEntryInfo, LinkRequirementInfo, LinkTaskInfo } from "@/stores/linkAux";
import { MoreOutlined } from "@ant-design/icons";
import UserPhoto from "@/components/Portrait/UserPhoto";

const PAGE_SIZE = 20;
const ShareList = () => {
    const history = useHistory();

    const userStore = useStores("userStore");
    const projectStore = useStores("projectStore");
    const appStore = useStores("appStore");
    const linkAuxStore = useStores("linkAuxStore");

    const [shareList, setShareList] = useState<ShareInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const loadShareList = async () => {
        const res = await request(list_share({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            filter_by_target_type: false,
            target_type: 0,
            filter_by_target_id: false,
            target_id: "",
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setShareList(res.share_info_list);
        setTotalCount(res.total_count);
    };

    const removeShare = async (shareId: string) => {
        await request(remove_share({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            share_id: shareId,
        }));
        await loadShareList();
        message.info("删除成功");
    };

    const copyShareUrl = async (shareId: string, shareSecret: string, open: boolean) => {
        const shareBaseUrl = appStore.clientCfg?.share_web_url ?? "";
        if (shareBaseUrl == "") {
            return;
        }
        const url = new URL(shareBaseUrl);
        if (url == null) {
            return;
        }
        url.searchParams.append("id", shareId);
        url.searchParams.append("secret", shareSecret);
        if (open) {
            await shell_open(url.toString());
        }
        await writeText(url.toString());
        message.info("已复制分享链接");
    };

    const columns: ColumnsType<ShareInfo> = [
        {
            title: "分享目标",
            render: (_, row: ShareInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if ([SHARE_TARGET_WORK_PLAN, SHARE_TARGET_DOC, SHARE_TARGET_DRAW].includes(row.target_type)) {
                        linkAuxStore.goToLink(new LinkEntryInfo("", projectStore.curProjectId, row.target_id), history);
                    } else if (row.target_type == SHARE_TARGET_TASK) {
                        linkAuxStore.goToLink(new LinkTaskInfo("", projectStore.curProjectId, row.target_id), history);
                    } else if (row.target_type == SHARE_TARGET_BUG) {
                        linkAuxStore.goToLink(new LinkBugInfo("", projectStore.curProjectId, row.target_id), history);
                    } else if (row.target_type == SHARE_TARGET_REQUIRE_MENT) {
                        linkAuxStore.goToLink(new LinkRequirementInfo("", projectStore.curProjectId, row.target_id), history);
                    }
                }}>{row.target_name}</a>
            ),
        },
        {
            title: "类型",
            width: 80,
            render: (_, row: ShareInfo) => get_type_name(row.target_type),
        },
        {
            title: "分享人",
            width: 150,
            render: (_, row: ShareInfo) => (
                <Space>
                    <UserPhoto logoUri={row.share_logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                    {row.share_display_name}
                </Space>
            ),
        },
        {
            title: "有效期限",
            render: (_, row: ShareInfo) => moment(row.expire_time).format("YYYY-MM-DD HH"),
        },
        {
            title: "操作",
            width: 120,
            render: (_, row: ShareInfo) => (
                <Space>
                    <Button type="primary" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        copyShareUrl(row.share_id, row.share_secret, true);
                    }}>复制链接</Button>
                    <Popover placement="bottom" trigger="click" content={
                        <Space direction="vertical">
                            <Button type="link" danger style={{ minWidth: 0, padding: "0px 0px" }}
                                disabled={!(row.share_user_id == userStore.userInfo.userId || projectStore.isAdmin)}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    removeShare(row.share_id);
                                }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>

                </Space>
            ),
        }
    ];

    useEffect(() => {
        loadShareList();
    }, [curPage]);

    return (
        <CardWrap title={
            <Space>
                分享列表
            </Space>
        } halfContent>
            <Table rowKey="share_id" dataSource={shareList} columns={columns} scroll={{ y: "calc(100vh - 250px)" }}
                pagination={{ current: curPage + 1, pageSize: PAGE_SIZE, total: totalCount, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
            />
        </CardWrap>
    );
};

export default observer(ShareList);